<template>
    <div class="module-wrapper">
        <DataGrid
            :auto-load="autoLoad"
            row-key="id"
            border
            default-expand-all
            ref="dataGridRef"
            :pagination="false"
            @selection-change="handleSelectionChange"
            showSelection
        >
            <template #toolbar-search>
                <div class="query-from-box">
                    <el-form>
                        <el-form-item>
                            <el-input v-model="queryData.deviceName" placeholder="设备组件名称" clearable />
                        </el-form-item>
                        <el-form-item>
                            <el-select v-model="queryData.enabled" placeholder="状态" clearable>
                                <el-option v-for="(value, key) in ModuletMode" :label="value" :key="key" :value="key" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
            </template>
            <template #toolbar-operation>
                <el-button type="primary" @click="onExport" :loading="exportLoading">导出</el-button>
                <el-button type="primary" @click="onModuleSync" :disabled="!tableData.length">模型同步</el-button>
                <el-tooltip
                    content="所选组件均尚未完成组件配置，不可设为使用"
                    placement="top"
                    :disabled="isBatchEnableBtnDis()"
                >
                    <el-button
                        type="primary"
                        @click="onBatchEnable()"
                        :disabled="!(enabledTableSelectId && enabledTableSelectId.length)"
                    >
                        使用
                    </el-button>
                </el-tooltip>
                <el-button :icon="Guide" circle @click="$emit('changeMode')" />
            </template>
            <el-table-column type="index" label="序号" width="60" align="center" fixed />
            <el-table-column label="模型名称" width="280" fixed show-overflow-tooltip>
                <template #default="scope">
                    <span style="color: red" v-if="scope.row.tag && scope.row.tag.toLowerCase() === 'new'">新</span>
                    <el-button link type="primary" @click="onGoPage(scope.row)"
                        >{{ scope.row.objectDisplayName
                        }}{{
                            detailData?.componentCount && !scope.$index ? `（${detailData?.componentCount}）` : ''
                        }}</el-button
                    >
                </template>
            </el-table-column>
            <el-table-column prop="deviceName" label="组件名称" show-overflow-tooltip />
            <el-table-column prop="slot" label="槽号" />
            <el-table-column prop="deviceNo" label="组件编号" />
            <el-table-column label="状态">
                <template #default="scope">
                    <span class="table-item-status" :status="scope.row.enabled ? '使用' : '未使用'" v-if="scope.$index">
                        {{ scope.row.enabled ? '使用' : '未使用' }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="110" fixed="right">
                <template #default="scope">
                    <template v-if="scope.$index">
                        <el-button link type="primary" @click="onModuleSet(scope.row)">设置 </el-button>
                        <el-button link type="primary" v-if="scope.row.enabled" @click="onDisable(scope.row)">
                            未使用
                        </el-button>
                        <el-tooltip
                            v-else
                            content="该组件尚未完成组件配置，不可设为使用"
                            placement="top"
                            :disabled="scope.row.deviceNo ? true : false"
                        >
                            <el-button
                                link
                                type="primary"
                                :disabled="!scope.row.deviceNo"
                                @click="onBatchEnable(scope.row)"
                            >
                                使用
                            </el-button>
                        </el-tooltip>
                    </template>
                </template>
            </el-table-column>
        </DataGrid>
    </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { IoTDeviceService, modelThingService } from '@great/services';
import { showPopupBox } from '@great/utils';
import ModuleSetModal from './ModuleSetModal.vue';
import { DataGrid, type DataGridInstance } from '@great/components';
import { useRoute } from 'vue-router';
import { Guide } from '@element-plus/icons-vue';

const route = useRoute();

const props = defineProps<{
    detailData?: Record<string, any>;
}>();
const initDetail: any = inject('initDetail');
const attributeTypeList = inject<any>('AttributeTypeList');
enum ModuletMode {
    true = '使用',
    false = '未使用'
}

// 查询条件
const queryData = ref({
    deviceName: '',
    enabled: ''
});
const tableData = ref([]);
const $emit = defineEmits<{
    (e: 'changeMode'): void;
}>();
const exportLoading = ref(false);
const dataGridRef = useTemplateRef<DataGridInstance>('dataGridRef');
const autoLoad = reactive({
    debounce: true,
    reloadDeps: [queryData],
    onLoad: async () => {
        const res = await IoTDeviceService.getTreeDevice({
            ...queryData.value,
            id: props.detailData?.id || route.params.id
        });
        tableData.value = res.data;
        return { data: res.data };
    }
});

// 表格勾选数据
const tableSelect = ref<unknown[]>([]);
const enabledTableSelectId = ref<unknown[]>([]);
const notSetSelectId = ref<unknown[]>([]);
// 表格勾选
const handleSelectionChange = (val: unknown[]) => {
    tableSelect.value = val;
    enabledTableSelectId.value = [];
    notSetSelectId.value = [];
    val.forEach((item: any) => {
        if (item.parentId != -1 && !item.enabled) {
            if (item.deviceNo) {
                enabledTableSelectId.value.push(item.id);
            } else {
                notSetSelectId.value.push(item);
            }
        }
    });
};
const onModuleSet = rowData => {
    showPopupBox(ModuleSetModal, {
        attributeTypeList,
        callback: dataGridRef.value?.refresh as () => Promise<void>,
        rowData
    });
};

const isBatchEnableBtnDis = (): boolean => {
    let isDis = true;
    if (notSetSelectId.value.length && !enabledTableSelectId.value.length) {
        isDis = false;
    }
    return isDis;
};

// 批量使用
const onBatchEnable = (row?: { id: number }) => {
    let htmlStr = `<div>确认${row ? '' : '批量'}使用设备？</div>`;
    if (!row && notSetSelectId.value.length) {
        let strItem = '';
        notSetSelectId.value.forEach((item: any) => {
            strItem = strItem + `<div>${item.deviceName}</div>`;
        });
        htmlStr = `<div>
            <div style="display: flex;">
                <i class="el-icon el-message-box__status el-message-box-icon--warning"><svg viewBox="0 0 1024 1024"><path fill="currentColor" d="M512 64a448 448 0 1 1 0 896 448 448 0 0 1 0-896m0 192a58.43 58.43 0 0 0-58.24 63.744l23.36 256.384a35.072 35.072 0 0 0 69.76 0l23.296-256.384A58.43 58.43 0 0 0 512 256m0 512a51.2 51.2 0 1 0 0-102.4 51.2 51.2 0 0 0 0 102.4"></path></svg></i>
                <strong style="padding-left:5px;">以下组件尚未完成组件配置，不可设为使用：</strong>
            </div>
            <div style="width: 390px;max-height: 100px;overflow: auto;padding-left:30px;">${strItem}</div>
            <strong>是否将其他已完成组件配置的组件，设置为使用？</strong>
        <div>`;
    }
    ElMessageBox.confirm(htmlStr, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true,
        type: !row && notSetSelectId.value.length ? '' : 'warning'
    })
        .then(async () => {
            // 接口请求
            await IoTDeviceService.batchEnableDevice(row ? [row.id] : enabledTableSelectId.value);
            ElNotification({
                title: '使用成功！',
                type: 'success'
            });
            dataGridRef.value?.refresh();
        })
        .catch(() => {});
};
// 停用
const onDisable = async (row: { id: number }) => {
    ElMessageBox.confirm(`确认将设备及设备下任务一起停用？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            await IoTDeviceService.batchDisableDevice([row?.id as number]);
            ElNotification({
                title: '停用成功！',
                type: 'success'
            });
            dataGridRef.value?.refresh();
        })
        .catch(() => {});
};
// 模型同步
const onModuleSync = async () => {
    const res = await IoTDeviceService.mergeDeviceTree({ id: (tableData.value[0] as any).id });
    const newTag = res.data.filter(item => item.tag && item.tag.toLowerCase() == 'new');
    ElNotification({
        title: `最新添加模型${newTag ? newTag.length : 0}个，已在列表内标注【新】`,
        type: 'success'
    });
    initDetail();
    dataGridRef.value?.refresh();
};
// 导出
const onExport = () => {
    exportLoading.value = true;
    modelThingService
        .exportThingTsl({
            proObjectName: props.detailData?.objectName,
            thingQuery: ['EVENT', 'ACTION', 'ATTRIBUTE', 'PROFILE'],
            proDeviceNo: props.detailData?.deviceNo
        })
        .then(() => {
            exportLoading.value = false;
        });
};

// 页面跳转（需求已废弃）
const onGoPage = row => {
    // router.push({
    //     name: 'model-thing-detail',
    //     params: {
    //         id: row?.objectId
    //     }
    // });
};
</script>
<style scoped lang="scss">
.module-wrapper {
    .query-from-box {
        display: flex;
        align-items: center;
        .el-form {
            display: flex;
            .el-form-item {
                margin-bottom: 0;
                width: 192px;
            }
            .el-form-item + .el-form-item {
                margin-left: 10px;
            }
        }
    }
    :deep(.data-grid) {
        .table-item-status {
            display: flex;
            align-items: center;
            &::before {
                content: '';
                width: 6px;
                height: 6px;
                display: inline-block;
                border-radius: 50%;
                margin-right: 5px;
            }
        }
        .table-item-status[status='未使用'] {
            &::before {
                background-color: #909399;
            }
        }
        .table-item-status[status='使用'] {
            &::before {
                background-color: #67c23a;
            }
        }
    }
}
</style>
